define(['ionic', 'ngMessages'], function () {

    angular.module('SaleRanking', ['ionic', 'ngMessages'])
        .run(function () {
            u9.hideLoading();
        })
        /******路由配置******/
        .config(['$stateProvider', '$urlRouterProvider', '$ionicConfigProvider', function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
            $stateProvider
                .state('main', {
                    url: '/main',
                    templateUrl: 'tpls/main.html',
                    controller: 'MainCtrl'
                });
            $urlRouterProvider.otherwise('/main');

            $ionicConfigProvider.platform.android.navBar.alignTitle('center');
            $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.android.navBar.transition('view');
            $ionicConfigProvider.platform.android.views.transition('ios');
            $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
            $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
            $ionicConfigProvider.platform.android.tabs.style('standard');
            $ionicConfigProvider.platform.android.tabs.position('bottom');
            $ionicConfigProvider.platform.android.form.toggle('large');

            $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.default.backButton.text(false);

            $ionicConfigProvider.views.maxCache(0);
        }])

        /******指令******/
        .directive('slideTab', ['$timeout', function($timeout) {
            return {
                restrict: 'E',
                scope: {
                    tabs: '=',
                    start: '@',
                    displayField: '@',
                    cssClass: '@',
                    onTabSelect: '&'
                },
                replace: true,
                template:
                    '<div class="tabs" ng-class="cssClass">' +
                        '<div class="tab-box"></div>' +
                        '<a class="tab-item" ng-repeat="tab in tabs" ng-click="onClick($index)">' +
                            '<span>{{tab[displayField]}}</span>' +
                        '</a>' +
                    '</div>',
                link: function($scope, $element, $attr) {
                    $timeout(init);

                    $scope.onClick = function (index) {
                        translate(index, 160);
                        updateTab(-1);
                        $timeout(function () {
                            updateTab(index);
                        }, 160);
                        $scope.onTabSelect && $scope.onTabSelect({index: index});
                    };

                    function init () {
                        var tabs = $element.find('a'),
                            tabBox = $element[0].children[0],
                            style = tabBox && tabBox.style;

                        if (style) {
                            style.width = tabs[0].offsetWidth + 'px';
                        }
                        var start = parseInt($attr.start) || 0;
                        translate(start, 0);
                        updateTab(start);
                    }

                    function translate(to, speed) {

                        var tabBox = $element[0].children[0];
                        var style = tabBox && tabBox.style;

                        if (!style) return;

                        var clientWidth = window.innerWidth,
                            tabs = $element.find('a'),
                            tabsWidth = tabs[0].offsetWidth * tabs.length;
                        var dist = (clientWidth - tabsWidth) / 2 + tabs[0].offsetWidth * to;

                        style.webkitTransitionDuration =
                            style.MozTransitionDuration =
                                style.msTransitionDuration =
                                    style.OTransitionDuration =
                                        style.transitionDuration = speed + 'ms';

                        style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
                        style.msTransform =
                            style.MozTransform =
                                style.OTransform = 'translateX(' + dist + 'px)';

                    }

                    function updateTab (index) {
                        var tabs = $element.find('a'),
                            el;
                        angular.forEach(tabs, function (tab, i) {
                            el = angular.element(tab);
                            if (i === index) {
                                el.addClass('active');
                            } else {
                                el.removeClass('active');
                            }
                        });
                    }
                }
            };
        }])

        .directive('performanceNum', function () {
            return {
                restrict: 'E',
                replace: true,
                scope: {
                    num: '=?',
                    symbol: '=?',
                    trend: '=?'
                },
                template:
                    '<label class="pref-num">' +
                        '<i class="icon" ng-class="{' + "'ion-social-yen':symbol==='CNY','ion-social-usd':symbol==='USD'" + '}"></i>' +
                        '<span>' +
                            '{{num | number}}' +
                        '</span>' +
                        '<i class="icon" ng-class="{' + "'ion-ios-arrow-thin-up':trend===1,'ion-ios-minus-empty':trend===0,'ion-ios-arrow-thin-down':trend===-1" + '}"></i>' +
                    '</label>'
            };
        })

        /******服务******/
        .constant('SaleRankingConstants', {
            PERIOD_TYPE_ARRAY: [{
                type: 'WEEK',
                name: '本周'
            }, {
                type: 'MONTH',
                name: '本月'
            }, {
                type: 'QUARTER',
                name: '本季'
            }, {
                type: 'YEAR',
                name: '本年'
            }],
            DISPLAY_NUM: 10,
            GetPeriodRankingCmd: 'UFIDA.U9.ISV.SM.IQuerySoTotalMoneyGroupBySellerSV'
        })

        .factory('rankingService', ['$q', '$filter', 'SaleRankingConstants', function ($q, $filter, SPRankConstants) {
            var o = {},
                rankCache = {},
                sealCache = {};

            o.getPeriodRankings = function (period) {
                var defer = $q.defer();

                if (period === '') {
                    defer.reject();
                } else if (rankCache.hasOwnProperty(period)) {
                    defer.resolve(angular.copy(rankCache[period]));
                } else {
                    var orgCode = u9.getLoginData().OrgCode;
                    u9.showLoading();
                    u9.callSV({
                        name: SPRankConstants.GetPeriodRankingCmd,
                        params: [orgCode, period],
                        onSuccess: function (data) {
                            rankCache[period] = formatPeriodRankings(data);
                            u9.hideLoading();
                            defer.resolve(angular.copy(rankCache[period]));
                        },
                        onFailure: function () {
                            u9.hideLoading();
                            defer.reject();
                        }
                    });
                }

                return defer.promise;
            };
            o.getRanking = function (period, userId) {
                var periodRankings = rankCache[period],
                    len = periodRankings.length;
                if (len === 0) {
                    return null;
                }
                for (var i = 0; i < len; i++) {
                    if (periodRankings[i].id === userId) {
                        return formatRanking(periodRankings[i], len);
                    }
                }
                return formatRanking(periodRankings[0], len);
            };
            o.getSeal = function (userId) {
                return sealCache[userId];
            };

            return o;

            function formatPeriodRankings (periodRankings) {
                periodRankings = $filter('orderBy')(periodRankings, 'CurTotalMoney', true);
                var tempArray = [],
                    rank = 1,
                    tempMoney = periodRankings.length > 0 ? periodRankings[0].CurTotalMoney : 0;
                angular.forEach(periodRankings, function (periodRanking, i) {
                    if (periodRanking.Userid != -1) {
                        if (periodRanking.CurTotalMoney < tempMoney) {
                            tempMoney = periodRanking.CurTotalMoney;
                            rank++;
                        }
                        var tempRanking = {};
                        tempRanking.id = periodRanking.Usercode;
                        tempRanking.rank = rank;
                        tempRanking.name = periodRanking.Username;
                        tempRanking.num = periodRanking.CurTotalMoney;
                        tempRanking.symbol = periodRanking.Symbol;
                        if (!sealCache.hasOwnProperty(periodRanking.Usercode) && periodRanking.Seal) {
                            sealCache[periodRanking.Usercode] = 'data:image/png;base64,' + periodRanking.Seal;
                        }
                        if (periodRanking.CurTotalMoney === periodRanking.LastTotalMoney) {
                            tempRanking.trend = 0;
                        } else {
                            tempRanking.trend = (periodRanking.CurTotalMoney > periodRanking.LastTotalMoney) ? 1 : -1;
                        }
                        tempArray.push(tempRanking);
                    }
                });
                return tempArray;
            }

            function formatRanking (ranking, len) {
                return {
                    name: ranking.name,
                    num: ranking.num,
                    symbol: ranking.symbol,
                    trend: ranking.trend,
                    rank: ranking.rank,
                    photo: sealCache[ranking.id],
                    fight: (len > 1) ? parseInt((len - ranking.rank) * 100 / (len - 1)) : 0
                };
            }
        }])

        /******控制器******/
        .controller('MainCtrl', ['$scope', 'rankingService', 'SaleRankingConstants',
            function ($scope, rankingService, SaleRankingConstants) {
                $scope.data = {
                    periodArray: SaleRankingConstants.PERIOD_TYPE_ARRAY,
                    selected: 1,
                    searchName: '',
                    current: null,
                    performances: [],
                    displayNum: SaleRankingConstants.DISPLAY_NUM,
                    noMoreData: true,
                    error: {
                        failed: false,
                        empty: false
                    }
                };

                setTabIndex($scope.data.selected);

                $scope.onTabSelected = function (tabIndex) {
                    setTabIndex(tabIndex);
                };
                $scope.resetPref = function (userId) {
                    var periodType = SaleRankingConstants.PERIOD_TYPE_ARRAY[$scope.data.selected].type;
                    $scope.data.current = rankingService.getRanking(periodType, userId);
                };
                $scope.loadMore = function () {
                    if ($scope.data.performances && $scope.data.performances.length != 0) {
                        if ($scope.data.performances.length > $scope.data.displayNum) {
                            $scope.data.displayNum += SaleRankingConstants.DISPLAY_NUM;
                        } else {
                            $scope.data.noMoreData = true;
                        }
                    } else {
                        $scope.data.noMoreData = true;
                    }
                    $scope.$broadcast('scroll.infiniteScrollComplete');
                };
                $scope.clearSearch = function () {
                    $scope.data.searchName = '';
                };

                function setTabIndex (index) {
                    $scope.data.selected = index;
                    var periodType = SaleRankingConstants.PERIOD_TYPE_ARRAY[index].type;
                    rankingService.getPeriodRankings(periodType).then(function (data) {
                        angular.forEach(data, function (rank) {
                            rank.photo = rankingService.getSeal(rank.id);
                        });

                        $scope.data.displayNum = SaleRankingConstants.DISPLAY_NUM;
                        $scope.data.noMoreData = false;

                        $scope.data.performances = data;
                        var userId = u9.getLoginData().UserCode;
                        $scope.data.current = rankingService.getRanking(periodType, userId);

                        $scope.data.error.failed = false;
                        if (data.length > 0) {
                            $scope.data.error.empty = false;
                        } else {
                            $scope.data.error.empty = true;
                        }
                    }, function () {
                        $scope.data.performances = [];
                        $scope.data.current = null;
                        $scope.data.error.failed = true;
                        $scope.data.error.empty = false;
                    });
                }
            }
        ]);
});